package hupu.hnlp.hot_buffer.front.controller;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Enumeration;
import java.util.Optional;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;

import hupu.hnlp.hot_buffer.front.appconfig.AppConfig;

public class BaseController
{
    @SuppressWarnings("unused")
    private final static Logger logger = LoggerFactory
            .getLogger(BaseController.class);

    @Resource(name = "appconfig")
    protected AppConfig appconfig;

    @Resource
    protected ObjectMapper objectMapper;

    @InitBinder
    public void initBinder(WebDataBinder binder)
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class,
                new CustomDateEditor(dateFormat, true));
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    public String index()
    {
        return String.format("ok %s", DateTimeFormatter
                .ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
    }

    protected SortedMap<String, String> get_request_params(
            HttpServletRequest request) throws Exception
    {
        SortedMap<String, String> params = new TreeMap<>();

        Enumeration<String> en = request.getParameterNames();
        while (en.hasMoreElements())
        {
            String key = ((String) en.nextElement()).trim();
            String val = Optional.ofNullable(request.getParameter(key))
                    .map(String::trim).orElse("");
            if (val.isEmpty())
                continue;
            params.put(key, val);
        }

        return params;
    }
}
